<!DOCTYPE html>
<html>
  <head>
    <title>智慧弈星</title>
    <style>
      body {
        display: flex;
        flex-direction: column;
        align-items: center;
        background: #f0f0f0;
        font-family: Arial, sans-serif;
      }

      #game-container {
        position: relative;
        margin: 20px;
        background: #e8c87e;
        border-radius: 10px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
      }

      #chessboard {
        cursor: pointer;
      }

      .control-panel {
        margin: 20px;
        display: flex;
        gap: 20px;
      }

      button {
        padding: 12px 24px;
        font-size: 16px;
        border: none;
        border-radius: 25px;
        background: #4caf50;
        color: white;
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      }

      button:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 8px rgba(0, 0, 0, 0.2);
      }

      #status {
        font-size: 24px;
        color: #333;
        margin: 10px;
      }
    </style>
  </head>
  <body>
    <div id="status">当前玩家：黑棋</div>
    <div id="game-container">
      <canvas id="chessboard" width="480" height="480"></canvas>
    </div>
    <div class="control-panel">
      <button onclick="startGame('pvp')">双人对战</button>
      <button onclick="startGame('ai')">人机对战</button>
      <button onclick="resetGame()">重新开始</button>
    </div>

    <script>
      const canvas = document.getElementById("chessboard");
      const ctx = canvas.getContext("2d");
      const GRID_SIZE = 15;
      const CELL_SIZE = canvas.width / (GRID_SIZE + 1);

      let board = Array(GRID_SIZE)
        .fill()
        .map(() => Array(GRID_SIZE).fill(0));
      let currentPlayer = 1; // 1: 黑棋, -1: 白棋
      let gameMode = "pvp";
      let gameOver = false;

      function drawBoard() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 绘制棋盘线
        ctx.strokeStyle = "#333";
        ctx.lineWidth = 1;
        for (let i = 0; i < GRID_SIZE; i++) {
          const pos = (i + 1) * CELL_SIZE;
          // 竖线
          ctx.beginPath();
          ctx.moveTo(pos, CELL_SIZE);
          ctx.lineTo(pos, canvas.height - CELL_SIZE);
          ctx.stroke();
          // 横线
          ctx.beginPath();
          ctx.moveTo(CELL_SIZE, pos);
          ctx.lineTo(canvas.width - CELL_SIZE, pos);
          ctx.stroke();
        }
      }

      function drawPiece(x, y, player) {
        ctx.beginPath();
        ctx.arc(
          (x + 1) * CELL_SIZE,
          (y + 1) * CELL_SIZE,
          CELL_SIZE * 0.4,
          0,
          Math.PI * 2
        );
        ctx.fillStyle = player === 1 ? "#000" : "#fff";
        ctx.shadowColor = "rgba(0,0,0,0.3)";
        ctx.shadowBlur = 5;
        ctx.fill();
      }

      function getBestMove() {
        // 简单AI逻辑：寻找最优得分位置
        let bestScore = -Infinity;
        let bestMoves = [];

        for (let y = 0; y < GRID_SIZE; y++) {
          for (let x = 0; x < GRID_SIZE; x++) {
            if (board[y][x] === 0) {
              let score = evaluatePosition(x, y, -currentPlayer);
              if (score > bestScore) {
                bestScore = score;
                bestMoves = [{ x, y }];
              } else if (score === bestScore) {
                bestMoves.push({ x, y });
              }
            }
          }
        }

        return bestMoves.length > 0
          ? bestMoves[Math.floor(Math.random() * bestMoves.length)]
          : null;
      }

      function evaluatePosition(x, y, player) {
        // 简单评分逻辑（可扩展优化）
        let score = 0;
        const directions = [
          [1, 0],
          [0, 1],
          [1, 1],
          [1, -1],
        ];

        directions.forEach(([dx, dy]) => {
          let count = 1;
          // 正向检测
          for (let i = 1; i < 5; i++) {
            const nx = x + dx * i;
            const ny = y + dy * i;
            if (
              nx >= 0 &&
              nx < GRID_SIZE &&
              ny >= 0 &&
              ny < GRID_SIZE &&
              board[ny][nx] === player
            ) {
              count++;
            } else break;
          }
          // 反向检测
          for (let i = 1; i < 5; i++) {
            const nx = x - dx * i;
            const ny = y - dy * i;
            if (
              nx >= 0 &&
              nx < GRID_SIZE &&
              ny >= 0 &&
              ny < GRID_SIZE &&
              board[ny][nx] === player
            ) {
              count++;
            } else break;
          }
          if (count >= 5) score += 1000;
          else score += Math.pow(10, count);
        });

        return score;
      }

      function checkWin(x, y) {
        const directions = [
          [1, 0],
          [0, 1],
          [1, 1],
          [1, -1],
        ];
        for (let [dx, dy] of directions) {
          let count = 1;
          for (let i = 1; i < 5; i++) {
            const nx = x + dx * i;
            const ny = y + dy * i;
            if (
              nx >= GRID_SIZE ||
              ny >= GRID_SIZE ||
              nx < 0 ||
              ny < 0 ||
              board[ny][nx] !== currentPlayer
            )
              break;
            count++;
          }
          for (let i = 1; i < 5; i++) {
            const nx = x - dx * i;
            const ny = y - dy * i;
            if (
              nx >= GRID_SIZE ||
              ny >= GRID_SIZE ||
              nx < 0 ||
              ny < 0 ||
              board[ny][nx] !== currentPlayer
            )
              break;
            count++;
          }
          if (count >= 5) return true;
        }
        return false;
      }

      canvas.addEventListener("click", (e) => {
        if (gameOver) return;

        const rect = canvas.getBoundingClientRect();
        const x = Math.round((e.clientX - rect.left - CELL_SIZE) / CELL_SIZE);
        const y = Math.round((e.clientY - rect.top - CELL_SIZE) / CELL_SIZE);

        if (
          x >= 0 &&
          x < GRID_SIZE &&
          y >= 0 &&
          y < GRID_SIZE &&
          board[y][x] === 0
        ) {
          placePiece(x, y);
        }
      });

      function placePiece(x, y) {
        board[y][x] = currentPlayer;
        drawPiece(x, y, currentPlayer);

        if (checkWin(x, y)) {
          gameOver = true;
          document.getElementById("status").textContent = `${
            currentPlayer === 1 ? "黑棋" : "白棋"
          }获胜！`;
          return;
        }

        currentPlayer *= -1;
        document.getElementById("status").textContent = `当前玩家：${
          currentPlayer === 1 ? "黑棋" : "白棋"
        }`;

        if (gameMode === "ai" && currentPlayer === -1 && !gameOver) {
          setTimeout(() => {
            const move = getBestMove();
            if (move) placePiece(move.x, move.y);
          }, 500);
        }
      }

      function startGame(mode) {
        gameMode = mode;
        resetGame();
        if (mode === "ai" && currentPlayer === -1) {
          setTimeout(() => {
            const move = getBestMove();
            if (move) placePiece(move.x, move.y);
          }, 500);
        }
      }

      function resetGame() {
        board = Array(GRID_SIZE)
          .fill()
          .map(() => Array(GRID_SIZE).fill(0));
        currentPlayer = 1;
        gameOver = false;
        document.getElementById("status").textContent = "当前玩家：黑棋";
        drawBoard();
      }

      // 初始化
      drawBoard();
    </script>
  </body>
</html>
